<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Picture, User, Plus } from '@element-plus/icons-vue'
import { useHttp } from '@/hooks/useHttp'
import { guildMemberListApi, updateMemberAnchorRationApi, addMemberAnchorApi, kickGuildMemberApi, type GuildMemberInfo, type GuildMemberListReq } from '@/api/union'
import { checkUserNoApi, type UserBaseInfo } from '@/api/user'
import { useRoute } from 'vue-router'

const route = useRoute()

// 获取工会编号
const guildNo = ref(route.query.guildNo as string)

// 监听路由变化
watch(() => route.query.guildNo, (newGuildNo) => {
  console.log('路由参数变化:', newGuildNo)
  guildNo.value = newGuildNo as string
  if (newGuildNo) {
    loadData()
  }
})

// 搜索参数
const searchParams = reactive<Omit<GuildMemberListReq, 'guildNo'>>({
  userNo: '', // 用户编号
  nickName: '',
  startDate: '',
  endDate: '',
  pageIndex: 1,
  pageSize: 20
})



// 使用封装的 useHttp hook
const { 
  dataList,
  loading,
  totals,
  pageInfo,
  loadData,
  handleSizeChange,
  handleCurrentChange,
  resetPagination
} = useHttp<GuildMemberInfo>("/guild/member-list", searchParams, {
  pageKey: 'pageIndex',
  pageSizeKey: 'pageSize',
  totalKey: 'total',
  listKey: 'list',
  customApi: (params) => {
    if (!guildNo.value) {
      ElMessage.error('请输入工会编号')
      return Promise.reject(new Error('请输入工会编号'))
    }
    return guildMemberListApi(guildNo.value, params)
  }
})

// 查询方法
const handleSearch = () => {
  if (!guildNo.value) {
    ElMessage.error('请输入工会编号')
    return
  }
  resetPagination()
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
}

// 重置方法
const handleReset = () => {
  // 重置搜索参数
  searchParams.userNo = ''
  searchParams.nickName = ''
  searchParams.startDate = ''
  searchParams.endDate = ''
  
  // 重置工会编号
  guildNo.value = ''
  
  // 重置分页
  resetPagination()
  
  // 清空数据列表
  dataList.value = []
  totals.value = 0
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化数字
const formatNumber = (num: number) => {
  if (num === 0) return '0'
  return num.toLocaleString()
}

// 获取成员状态文本
const getMemberStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '正常'
    case 1:
      return '待审核'
    default:
      return '未知'
  }
}

// 获取成员状态类型
const getMemberStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'success'
    case 1:
      return 'warning'
    default:
      return 'info'
  }
}

// 修改分成比例相关
const ratioDialogVisible = ref(false)
const currentMember = ref<GuildMemberInfo | null>(null)
const updateLoading = ref(false)
const ratioFormRef = ref()

const ratioForm = reactive({
  anchorRation: 0
})

const ratioRules = {
  anchorRation: [
    { required: true, message: '请输入分成比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '分成比例必须在0-100之间', trigger: 'blur' }
  ]
}

// 添加主播相关
const addMemberDialogVisible = ref(false)
const addMemberLoading = ref(false)
const addMemberFormRef = ref()
const userValidating = ref(false)
const userValidationError = ref('')
const userValidationSuccess = ref(false)
const userInfo = ref<UserBaseInfo | null>(null)

const addMemberForm = reactive({
  userNo: ''
})

const addMemberRules = {
  userNo: [
    { required: true, message: '请输入主播ID', trigger: 'blur' }
  ]
}

// 剔除成员相关
const removeMemberDialogVisible = ref(false)
const removeMemberLoading = ref(false)
const currentRemoveMember = ref<GuildMemberInfo | null>(null)
const removeReason = ref('')

// 处理修改分成比例
const handleUpdateRatio = (member: GuildMemberInfo) => {
  currentMember.value = member
  ratioForm.anchorRation = member.anchorRation
  ratioDialogVisible.value = true
}

// 添加主播
const handleAddMember = () => {
  if (!guildNo.value) {
    ElMessage.error('请先输入工会编号')
    return
  }
  
  // 重置表单和验证状态
  addMemberForm.userNo = ''
  userValidationError.value = ''
  userValidationSuccess.value = false
  userInfo.value = null
  
  // 打开添加主播弹窗
  addMemberDialogVisible.value = true
}

// 校验主播ID
const handleValidateUser = async () => {
  if (!addMemberForm.userNo) {
    userValidationError.value = '请输入主播ID'
    return
  }
  
  userValidating.value = true
  userValidationError.value = ''
  userValidationSuccess.value = false
  userInfo.value = null
  
  try {
    const response = await checkUserNoApi(addMemberForm.userNo)
    if (response.code === 200 && response.data) {
      userInfo.value = response.data
      userValidationSuccess.value = true
      userValidationError.value = ''
    } else {
      userValidationError.value = '用户不存在'
      userValidationSuccess.value = false
    }
  } catch (error) {
    console.error('校验用户失败:', error)
    userValidationError.value = '校验失败，请重试'
    userValidationSuccess.value = false
  } finally {
    userValidating.value = false
  }
}

// 处理剔除成员
const handleRemoveMember = (member: GuildMemberInfo) => {
  currentRemoveMember.value = member
  removeReason.value = ''
  removeMemberDialogVisible.value = true
}

// 确认剔除成员
const handleConfirmRemoveMember = async () => {
  if (!currentRemoveMember.value) return
  
  try {
    removeMemberLoading.value = true
    
    // 调用后端API剔除成员
    await kickGuildMemberApi({
      guildNo: guildNo.value,
      userNo: currentRemoveMember.value.userNo,
      reason: removeReason.value || undefined
    })
    
    ElMessage.success('成员剔除成功')
    removeMemberDialogVisible.value = false
    
    // 重新加载数据
    loadData()
  } catch (error) {
    console.error('剔除成员失败:', error)
    ElMessage.error('剔除成员失败')
  } finally {
    removeMemberLoading.value = false
  }
}

// 确认添加主播
const handleConfirmAddMember = async () => {
  if (!addMemberFormRef.value) return
  
  try {
    await addMemberFormRef.value.validate()
    
    if (!userValidationSuccess.value) {
      ElMessage.error('请先校验主播ID')
      return
    }
    
    addMemberLoading.value = true
    
    // 调用后端API添加主播
    await addMemberAnchorApi({
      guildNo: guildNo.value,
      userNo: addMemberForm.userNo
    })
    
    ElMessage.success('主播添加成功')
    addMemberDialogVisible.value = false
    
    // 重新加载数据
    loadData()
  } catch (error) {
    console.error('添加主播失败:', error)
    ElMessage.error('添加主播失败')
  } finally {
    addMemberLoading.value = false
  }
}

// 确认修改分成比例
const handleConfirmUpdateRatio = async () => {
  if (!ratioFormRef.value) return
  
  try {
    await ratioFormRef.value.validate()
    updateLoading.value = true
    
    // 调用后端API更新成员分成比例
    await updateMemberAnchorRationApi({
      guildNo: guildNo.value,
      userNo: currentMember.value!.userNo,
      anchorRation: ratioForm.anchorRation
    })
    
    ElMessage.success('分成比例修改成功')
    ratioDialogVisible.value = false
    
    // 重新加载数据
    loadData()
  } catch (error) {
    console.error('修改分成比例失败:', error)
    ElMessage.error('修改分成比例失败')
  } finally {
    updateLoading.value = false
  }
}

onMounted(() => {
  console.log('组件挂载，guildNo:', guildNo.value)
  console.log('路由查询参数:', route.query)
  if (guildNo.value) {
    loadData()
  }
  // 如果没有工会编号，不显示错误，让用户手动输入
})
</script>

<template>
  <div class="member-list">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="工会编号">
          <el-input
            v-model="guildNo"
            placeholder="请输入工会编号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="用户编号">
          <el-input
            v-model="searchParams.userNo"
            placeholder="请输入用户编号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input
            v-model="searchParams.nickName"
            placeholder="请输入用户昵称"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="searchParams.startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="searchParams.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAddMember">
            <el-icon><Plus /></el-icon>
            添加主播
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        :data="dataList"
        v-loading="loading"
        style="width: 100%"
        :fit="true"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" min-width="60" align="center" />
        <el-table-column label="用户头像" min-width="100" align="center">
          <template #default="{ row }">
            <el-image
              :src="row.user.avatar"
              :preview-src-list="[row.user.avatar]"
              fit="cover"
              style="width: 50px; height: 50px; border-radius: 50%; cursor: pointer;"
              :initial-index="0"
              preview-teleported
            >
              <template #error>
                <el-avatar :size="50">
                  <el-icon><Picture /></el-icon>
                </el-avatar>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="user-info">
              <div class="user-name">昵称: {{ row.user.nickname || '-' }}</div>
              <div class="user-id">ID: {{ row.user.userNo || '-' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="user.gender" label="性别" min-width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.user.gender === 0" type="info" size="small">男</el-tag>
            <el-tag v-else-if="row.user.gender === 1" type="danger" size="small">女</el-tag>
            <el-tag v-else type="warning" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user.countryCode" label="国家" min-width="100" align="center" />
        <el-table-column prop="user.appLanguage" label="语言" min-width="100" align="center" />
        <el-table-column label="累计金币收入" min-width="120" align="center">
          <template #default="{ row }">
            <span class="income-text">{{ formatNumber(row.totalCoinIncome) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="累计钻石收入" min-width="120" align="center">
          <template #default="{ row }">
            <span class="income-text">{{ formatNumber(row.totalDiamondIncome) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成员分成比例" min-width="120" align="center">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleUpdateRatio(row)"
              style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;"
            >
              {{ row.anchorRation }}%
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getMemberStatusType(row.status)" size="small">
              {{ getMemberStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="加入时间" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDate(row.joinTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="user.birth" label="生日" min-width="120" align="center" />
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleRemoveMember(row)"
            >
              剔除成员
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination 
        class="pagination-center mt"
        v-model:current-page="pageInfo.page" 
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="totals" 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" 
        background
      />
    </el-card>

    <!-- 修改成员分成比例弹窗 -->
    <el-dialog
      v-model="ratioDialogVisible"
      title="修改成员分成比例"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="ratioForm" :rules="ratioRules" ref="ratioFormRef" label-width="120px">
        <el-form-item label="用户信息">
          <div class="user-info-display">
            <el-avatar :size="40" :src="currentMember?.user?.avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="user-details">
              <div class="user-name">{{ currentMember?.user?.nickname }}</div>
              <div class="user-id">ID: {{ currentMember?.userNo }}</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="当前分成比例">
          <span class="current-ratio">{{ currentMember?.anchorRation }}%</span>
        </el-form-item>
        <el-form-item label="新分成比例" prop="anchorRation">
          <el-input-number
            v-model="ratioForm.anchorRation"
            :min="0"
            :max="100"
            :precision="0"
            placeholder="请输入分成比例"
            style="width: 200px"
          />
          <span class="ratio-unit">%</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ratioDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmUpdateRatio" :loading="updateLoading">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加主播弹窗 -->
    <el-dialog
      v-model="addMemberDialogVisible"
      title="添加主播"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="addMemberForm" :rules="addMemberRules" ref="addMemberFormRef" label-width="120px">
        <el-form-item label="工会编号">
          <span class="guild-no">{{ guildNo }}</span>
        </el-form-item>
        <el-form-item label="主播ID" prop="userNo">
          <el-input
            v-model="addMemberForm.userNo"
            placeholder="请输入主播ID"
            clearable
            style="width: 300px"
            @blur="handleValidateUser"
            :class="{ 'is-error': userValidationError }"
          />
          <el-button 
            type="primary" 
            size="small" 
            @click="handleValidateUser"
            :loading="userValidating"
            style="margin-left: 8px"
          >
            校验
          </el-button>
          <div v-if="userValidationError" class="validation-error">
            {{ userValidationError }}
          </div>
          <div v-if="userValidating" class="validating-text">
            正在校验用户信息...
          </div>
          <div v-if="userInfo && userValidationSuccess" class="user-info-display">
            <el-avatar :size="40" :src="userInfo.avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="user-details">
              <div class="user-name">{{ userInfo.nickname }}</div>
              <div class="user-id">ID: {{ userInfo.userNo }}</div>
              <div class="user-gender">
                {{ userInfo.gender === 0 ? '男' : userInfo.gender === 1 ? '女' : '未知' }}
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addMemberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAddMember" :loading="addMemberLoading">
            确认添加
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 剔除成员确认弹窗 -->
    <el-dialog
      v-model="removeMemberDialogVisible"
      title="剔除成员"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="remove-member-content">
        <div class="warning-icon">
          <el-icon size="48" color="#f56c6c"><Warning /></el-icon>
        </div>
        <div class="warning-text">
          <p>确定要将以下成员剔除出工会吗？</p>
          <p class="member-info">
            <strong>成员信息：</strong>
            {{ currentRemoveMember?.user?.nickname }} (ID: {{ currentRemoveMember?.userNo }})
          </p>
          <p class="warning-note">此操作不可撤销，请谨慎操作！</p>
        </div>
        <div class="reason-input">
          <el-form-item label="剔除原因" label-width="80px">
            <el-input
              v-model="removeReason"
              type="textarea"
              :rows="3"
              placeholder="请输入剔除原因（可选）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeMemberDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmRemoveMember" :loading="removeMemberLoading">
            确认剔除
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<style lang="less" scoped>
.member-list {
  .mb {
    margin-bottom: 20px;
  }
  
  .mt {
    margin-top: 20px;
  }
  
  .pagination-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  // 表格字体大小设置
  :deep(.el-table) {
    font-size: 14px;
    
    .el-table__header {
      th {
        font-size: 15px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .el-table__body {
      td {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  // 表格内容区域的字体大小
  :deep(.el-table__cell) {
    font-size: 14px;
  }

  // 用户信息样式
  .user-info {
    .user-name {
      font-weight: 500;
      margin-bottom: 4px;
      font-size: 15px;
    }
    
    .user-id {
      font-size: 13px;
      color: #909399;
    }
  }

  // 收入文本样式
  .income-text {
    color: #409eff;
    font-weight: 500;
    font-size: 15px;
  }

  // 标签样式调整
  :deep(.el-tag) {
    font-size: 13px;
  }

  // 用户信息显示样式
  .user-info-display {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .user-details {
      .user-name {
        font-weight: 500;
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .user-id {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  // 当前分成比例样式
  .current-ratio {
    font-weight: 500;
    color: #409eff;
    font-size: 16px;
  }

  // 分成比例单位样式
  .ratio-unit {
    margin-left: 8px;
    color: #606266;
    font-size: 14px;
  }

  // 工会编号样式
  .guild-no {
    font-weight: 500;
    color: #409eff;
    font-size: 16px;
  }

  // 验证错误样式
  .validation-error {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
  }

  // 验证中样式
  .validating-text {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
  }

  // 用户性别样式
  .user-gender {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }

  // 剔除成员弹窗样式
  .remove-member-content {
    text-align: center;
    padding: 20px 0;
    
    .warning-icon {
      margin-bottom: 20px;
    }
    
    .warning-text {
      p {
        margin: 10px 0;
        font-size: 16px;
        color: #303133;
        
        &.member-info {
          font-size: 14px;
          color: #606266;
          background: #f5f7fa;
          padding: 10px;
          border-radius: 4px;
          margin: 15px 0;
        }
        
        &.warning-note {
          color: #f56c6c;
          font-weight: 500;
          font-size: 14px;
        }
      }
    }
    
    .reason-input {
      margin-top: 20px;
      text-align: left;
      
      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #303133;
      }
      
      :deep(.el-textarea__inner) {
        border-color: #dcdfe6;
        
        &:focus {
          border-color: #409eff;
        }
      }
    }
  }
}
</style>